package org.modelcc.io.java.processor;

import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;

import org.modelcc.IModel;
import org.modelcc.Priority;
import org.modelcc.io.java.JavaLanguageClass;
import org.modelcc.io.java.JavaModelProcessor;
import org.modelcc.io.java.JavaModelReader;
import org.modelcc.io.java.JavaLanguageMetadata;

/**
 * Process priorities
 */
public class PriorityProcessor extends JavaModelProcessor<JavaLanguageMetadata>
{	
	public PriorityProcessor (JavaModelReader reader)
	{
		super(reader);
	}
	
	@Override
	public void process(JavaLanguageMetadata metadata) 
	{
		for (JavaLanguageClass pe: metadata.getJavaElements()) {
    		Class elementClass = pe.getElementClass();

    		Integer priority = null;
    		Set<JavaLanguageClass> precede = new HashSet<JavaLanguageClass>();
    		if (elementClass.isAnnotationPresent(Priority.class)) {
    			Priority an;
    			an = (Priority) elementClass.getAnnotation(Priority.class);
    			priority = an.value();
    			for (int i = 0;i < an.precedes().length;i++) {
    				if (!IModel.class.isAssignableFrom(an.precedes()[i]))
    					log(Level.SEVERE, "In class \"{0}\": Preceded by class \"{1}\" but does not implement IModel.", new Object[]{an.precedes()[i].getCanonicalName(),elementClass.getCanonicalName()});
    				else
    					precede.add(metadata.getClassElement(an.precedes()[i]));
    			}
    		}
    		
    		if (!precede.isEmpty())
    			metadata.prePrecedences.put(pe, precede);
    		
    		metadata.prePriorities.put(pe, priority);
    	}
		
    }
}
